package com.wgo.precise.client.ui.view.util.celleditors;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.jface.viewers.DialogCellEditor;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import org.eclipse.jface.viewers.ViewerSorter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.ui.dialogs.ListDialog;
import org.eclipse.ui.dialogs.SelectionDialog;

import com.wgo.precise.client.ui.controller.ModelStatus;
import com.wgo.precise.client.ui.controller.RequirementPlugin;
import com.wgo.precise.client.ui.model.StakeholderWrapper;
import com.wgo.precise.client.ui.view.util.LinkListPropertySource;
import com.wgo.precise.client.ui.view.util.ModelItemLabelProvider;
import com.wgo.precise.client.ui.view.util.contentproviders.StakeholderViewContentProvider;
import com.wgo.precise.client.ui.view.util.viewfilters.StakeholderViewerFilter;


public class StakeholderCellEditor extends DialogCellEditor {
	private static final String singleTitle = "Stakeholder selection";
	private static final String multiTitle = "Stakeholder(s) selection" ;
	private static final String singleMessage = "Select none or one stakeholder";
	private static final String multiMessage = "Select none, one or more stakeholders." ;
	private String title = null;
	private String message = null;
	private static final int defaultDialogTableStyle = SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER;
	private int style = SWT.NONE;

	public StakeholderCellEditor(Composite parent, boolean multiSelect) {
		this(parent, multiSelect ? multiTitle : singleTitle, multiSelect ? multiMessage : singleMessage, ((multiSelect ? SWT.MULTI : SWT.SINGLE) | defaultDialogTableStyle ));
	}
	/**
	 * @param style could be SWT.MULTI or SWT.SINGLE
	 */
	public StakeholderCellEditor(Composite parent, String title, String message, int style) {
		super(parent);
		this.title = title;
		this.message = message;
		this.style = style | defaultDialogTableStyle;
	}
	public StakeholderCellEditor(Composite parent, String title, String message) {
		this(parent, title, message, SWT.SINGLE );
	}
	@Override
	protected Object openDialogBox(Control cellEditorWindow) {
		ListDialog dialog = new ListDialog(cellEditorWindow.getShell()) {
			@Override
			protected int getTableStyle() {
				return style;
			}
			@Override
			protected void createButtonsForButtonBar(Composite parent) {
				createClearButton(parent, "Clear");
				super.createButtonsForButtonBar(parent);
			}
		    protected Button createClearButton(Composite parent, String label){
		        // increment the number of columns in the button bar
		        ((GridLayout) parent.getLayout()).numColumns++;
		        Button button = new Button(parent, SWT.PUSH);
		        button.setText(label);
		        button.setFont(JFaceResources.getDialogFont());
		        button.addSelectionListener(new SelectionAdapter() {
		            @Override
					public void widgetSelected(@SuppressWarnings("unused") SelectionEvent event) {
		            	getTableViewer().setSelection(new ISelection() {
							public boolean isEmpty() {
								return true;
							}
		            	});
		            }
		        });
		        setButtonLayoutData(button);
		        return button;
		    }
			@Override
			protected Control createDialogArea(Composite container) {
				Control returnControl = super.createDialogArea(container);
				getTableViewer().addFilter(new StakeholderViewerFilter());
				getTableViewer().setComparator(new ViewerComparator(){

					/* (non-Javadoc)
					 * @see org.eclipse.jface.viewers.ViewerComparator#compare(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
					 */
					@Override
					public int compare(Viewer viewer, Object e1, Object e2) {
						if ( e1 instanceof StakeholderWrapper && e2 instanceof StakeholderWrapper){
							return super.compare(viewer, ((StakeholderWrapper)e1).getSimpleName(), ((StakeholderWrapper)e2).getSimpleName());
						}
						return super.compare(viewer, e1, e2);
					}
					
				});
				return returnControl;
			}
		    
		};
		dialog.setContentProvider(new StakeholderViewContentProvider());
		dialog.setLabelProvider(new ModelItemLabelProvider());
		dialog.setTitle(title);
		dialog.setInput(RequirementPlugin.getInstance().getSession().getWrapperFactory().getSystem(StakeholderWrapper.class));
		dialog.setMessage(message);
		if (null != getValue() && getValue() instanceof LinkListPropertySource) {
			List<IAdaptable> currentLinkedRequirements = ((LinkListPropertySource)getValue()).getItems();
			dialog.setInitialElementSelections(currentLinkedRequirements);
		} else if (getValue() != null) {
			RequirementPlugin.log(new ModelStatus(IStatus.WARNING, getClass() + " openDialogBox(): CellEditorValue had value of invalid type set."));
		}
		Object value = null;
//		if (dialog.open() == SelectionDialog.OK && dialog.getResult().length > 0){
		if (dialog.open() == SelectionDialog.OK ){
			Object[] result = dialog.getResult();
			List<IAdaptable> selected = new ArrayList<IAdaptable>();
			if (result != null && 0 < result.length) {
				for (Object object : result) {
					if (object instanceof IAdaptable) {
						IAdaptable adaptable = (IAdaptable) object;
						selected.add(adaptable);
					}
				}
			}
			value = new LinkListPropertySource(selected);
		}
		return value;
	}
}